<template>
  <div class="user">
    <!--搜索表单-->
    <div class="common-seach-wrap">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="">
          <el-select-v2
            v-model="formInline.vehicle_id"
            clearable
            :options="vehicles"
            :props="{
              label: 'model',
              value: 'id',
            }"
            :fit-input-width="600"
            style="width: 200px"
            placeholder="选择车型"
          >
            <template v-slot:header>
              <el-select v-model="vehicles_search.brands" placeholder="按品牌筛选" clearable>
                <el-option
                  v-for="(item, index) in brands"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
              <div class="letter-box">
                <div
                  class="letter-item"
                  :class="{ active: item == vehicles_search.firstletter }"
                  v-for="(item, index) in letter"
                  :key="index"
                  @click="setLetter(item)"
                >
                  {{ item }}
                </div>
              </div>
              <el-input
                v-model="vehicles_search.keyword"
                placeholder="搜索车型"
                clearable
                prefix-icon="Search"
              ></el-input>
              <div class="count-box">
                <div class="count-num">找到{{ vehicles.length }}个车型</div>
                <el-button
                  @click="vehicles_search.is_popular = !vehicles_search.is_popular"
                  type="warning"
                  icon="Star"
                  size="small"
                  :plain="!vehicles_search.is_popular"
                  >只看热门</el-button
                >
              </div>
            </template>
          </el-select-v2>
        </el-form-item>
        <el-form-item label="">
          <el-select v-model="formInline.product_id" placeholder="选择产品" style="width: 200px">
            <template #header>
              <el-tag
                :type="produtType == '窗膜' ? 'primary' : 'info'"
                @click="produtType = produtType == '窗膜' ? '' : '窗膜'"
                >窗膜</el-tag
              >
              <el-tag
                :type="produtType == '车衣' ? 'primary' : 'info'"
                style="margin-left: 10px"
                @click="produtType = produtType == '车衣' ? '' : '车衣'"
                >车衣</el-tag
              >
            </template>
            <el-option
              v-for="item in showProductOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-select v-model="formInline.sort" filterable placeholder="排序方式">
            <el-option
              v-for="item in sortOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-button type="" icon="Edit" @click="isAdvanced = !isAdvanced">{{
            isAdvanced ? "收起" : "高级搜索"
          }}</el-button>
        </el-form-item>
        <div class="advanced-search-panel" v-show="isAdvanced">
          <el-form :inline="true" :model="advancedSearch" class="demo-form-inline" size="small">
            <el-form-item label="价格范围">
              <el-input-number
                v-model="advancedSearch.minPrice"
                label="最小价格"
                :min="0"
                size="small"
              />
              至
              <el-input-number
                v-model="advancedSearch.maxPrice"
                label="最高价格"
                :min="0"
                size="small"
              />
            </el-form-item>
            <el-form-item label="生效日期">
              <el-date-picker
                v-model="advancedSearch.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="small"
              />
            </el-form-item>
            <el-form-item label="关键词搜索">
              <el-input
                v-model="advancedSearch.keyword"
                placeholder="搜索车型、产品等"
                clearable
                prefix-icon="Search"
              ></el-input>
            </el-form-item>
          </el-form>
          <div
            class="button-box"
            style="display: flex; justify-content: flex-end; margin-top: 10px"
          >
            <el-button type="primary" icon="Search" @click="getTableInfo()" size="small"
              >应用筛选</el-button
            >
            <el-button type="" icon="Delete" @click="resetAdvancedSearch()" size="small"
              >重置</el-button
            >
          </div>
        </div>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getTableInfo()">搜索</el-button>
          <el-button type="primary" icon="Plus" @click="handleInfo()">添加</el-button>
          <el-button
            type="warning"
            :disabled="selectedRows.length == 0"
            icon="Edit"
            @click="handlePrice()"
            >批量修改价格</el-button
          >
          <!-- <el-button
            type="success"
            :disabled="selectedRows.length == 0"
            icon="CopyDocument"
            @click="handleCopy()"
            >批量克隆</el-button
          >
          <el-button type="info" icon="MagicStick" @click="handleQuick()">快速添加</el-button> -->
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" header="快速筛选">
      <el-button
        :type="quickTagindex == index ? 'primary' : 'info'"
        :dark="true"
        size="small"
        v-for="(item, index) in quickTags"
        :key="index"
        @click="item.call"
        >{{ item.label }}</el-button
      >
    </el-card>
    <div class="count-tip">
      当前显示: {{ tableData.length }} 个价格策略(共 {{ totalDataNumber }} 个价格策略)
    </div>
    <div class="chart-box" v-loading="dataLoading">
      <div class="chart-title">
        <div class="chart-title-left">价格数据统计</div>
        <div class="chart-title-right">
          <el-switch v-model="chartSwitch" active-text="显示图表" inactive-text="隐藏图表" />
          <el-button
            type=""
            icon="Refresh"
            @click="getData()"
            size="small"
            style="margin-left: 10px"
            >刷新数据</el-button
          >
        </div>
      </div>
      <div class="card-box">
        <el-card shadow="hover">
          <div class="card-icon" style="background: #409eff">
            <el-icon color="#fff">
              <Money />
            </el-icon>
          </div>
          <div class="card-val">
            <div class="val">{{ totalDataNumber }}</div>
            <div class="label">价格策略总数</div>
          </div>
        </el-card>
        <el-card shadow="hover">
          <div class="card-icon" style="background: #67c23a" @click="vehiclesRef.dialogOpen()">
            <el-icon color="#fff">
              <Van />
            </el-icon>
          </div>
          <div class="card-val" @click="vehiclesRef.dialogOpen()">
            <div class="val">{{ coveredVehicles.length }}</div>
            <div class="label">覆盖车型数量</div>
          </div>
        </el-card>
        <el-card shadow="hover">
          <div class="card-icon" style="background: #e6a23c" @click="linkProductsRef.dialogOpen()">
            <el-icon color="#fff">
              <Box />
            </el-icon>
          </div>
          <div class="card-val" @click="linkProductsRef.dialogOpen()">
            <div class="val">{{ allProducts.length }}</div>
            <div class="label">关联产品数量</div>
          </div>
        </el-card>
        <el-card shadow="hover">
          <div class="card-icon" style="background: #f56c6c">
            <el-icon color="#fff">
              <PriceTag />
            </el-icon>
          </div>
          <div class="card-val">
            <div class="val">{{ averagePrice }}</div>
            <div class="label">平均价格</div>
          </div>
        </el-card>
        <el-card shadow="hover">
          <div class="card-icon" style="background: #8e44ad">
            <el-icon color="#fff">
              <Star />
            </el-icon>
          </div>
          <div class="card-val">
            <div class="val">{{ allBrands.length }}</div>
            <div class="label">覆盖品牌数量</div>
          </div>
        </el-card>
        <el-card shadow="hover">
          <div class="card-icon" style="background: #e74c3c" @click="hotVehiclesRef.dialogOpen()">
            <el-icon color="#fff">
              <WarningFilled />
            </el-icon>
          </div>
          <div class="card-val" @click="hotVehiclesRef.dialogOpen()">
            <div class="val">{{ hotVehicles.length }}</div>
            <div class="label">热门车型价格</div>
          </div>
        </el-card>
        <el-card shadow="hover">
          <div class="card-icon" style="background: #3498db">
            <el-icon color="#fff">
              <Timer />
            </el-icon>
          </div>
          <div class="card-val">
            <div class="val">{{ newVehicles.length }}</div>
            <div class="label">最近添加价格</div>
          </div>
        </el-card>
        <el-card shadow="hover">
          <div class="card-icon" style="background: #2ecc71">
            <el-icon color="#fff">
              <DataLine />
            </el-icon>
          </div>
          <div class="card-val">
            <div class="val">{{ minPrice }} - {{ maxPrice }}</div>
            <div class="label">价格区间分布</div>
          </div>
        </el-card>
      </div>
      <div class="chart-main" v-show="chartSwitch">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card shadow="hover">
              <template v-slot:header>
                <div class="chart-header">
                  <div class="chart-header-title">产品类型分布</div>
                  <el-icon size="16" @click="getData1()">
                    <Refresh />
                  </el-icon>
                </div>
              </template>
              <div id="productTypeChart" style="width: 100%; height: 300px"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card shadow="hover">
              <template v-slot:header>
                <div class="chart-header">
                  <div class="chart-header-title">价格区间分布</div>
                  <el-icon size="16" @click="getData2()">
                    <Refresh />
                  </el-icon>
                </div>
              </template>
              <!-- 添加价格区间分布图容器 -->
              <div id="priceRangeChart" style="width: 100%; height: 300px"></div>
            </el-card>
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px">
          <el-col :span="24">
            <el-card shadow="hover">
              <template v-slot:header>
                <div class="chart-header">
                  <div class="chart-header-title">热门品牌价格对比</div>
                  <el-icon size="16" @click="getData3()">
                    <Refresh />
                  </el-icon>
                </div>
              </template>
              <!-- 添加品牌分布图容器 -->
              <div id="brandChart" style="width: 100%; height: 400px"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </div>
    <!--内容-->
    <div class="product-content">
      <div class="table-wrap">
        <el-table
          size="small"
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="model" label="车型">
            <template #default="scope"> {{ scope.row.brand }} {{ scope.row.model }} </template>
          </el-table-column>
          <el-table-column prop="firstletter" label="产品信息" width="400">
            <template #default="scope">
              <b>{{ scope.row.product_name }}</b>
              <div class="tag-box">
                <el-tag type="primary" size="small">{{ scope.row.product_type }}</el-tag>
                <el-tag type="info" size="small">材质{{ scope.row.material }}</el-tag>
                <el-tag type="warning" size="small">质保{{ scope.row.warranty_years }}年</el-tag>
              </div>
              <div class="tag-box">
                特性：
                <el-tag
                  type="primary"
                  effect="plain"
                  size="small"
                  v-for="(t, index) in scope.row.features"
                  :key="index"
                  >{{ t }}</el-tag
                >
              </div>
              <div class="tag-box">
                覆盖：
                <el-tag
                  type="success"
                  effect="plain"
                  size="small"
                  v-for="(t, index) in scope.row.product_parts"
                  :key="index"
                  >{{ t }}</el-tag
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="" label="整套价格">
            <template #default="{ row }">
              <el-text type="danger">&yen;{{ row.base_price }}</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="" label="折扣后价格">
            <template #default="{ row }">
              <el-text type="danger">&yen;{{ row.base_price * row.discount_rate }}</el-text>
              <div></div>
              <el-tag type="danger" size="small" effect="plain"
                >{{ row.discount_rate * 100 }}%</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="" label="价格详情">
            <template #default="{ row }">
              <el-popover title="部位价格" placement="left">
                <template #reference>
                  <el-button type="primary" plain size="small">查看价格详情</el-button>
                </template>
                <el-text v-if="row.components.length == 0">暂无详细价格信息</el-text>
                <el-row v-for="(c, index) in row.components" :key="index">
                  <el-col :span="6">{{ c.component_key }}</el-col>
                  <el-col :span="18"
                    ><el-text type="danger">&yen;{{ c.price }}</el-text></el-col
                  >
                </el-row>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="effective_date" label="生效日期"></el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" icon="Edit" size="small" @click="handleInfo(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                icon="Delete"
                size="small"
                @click="handleDelete(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--分页-->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          :current-page="curPage"
          :page-size="pageSize"
          layout="total,sizes, prev, pager, next, jumper"
          :total="totalDataNumber"
        ></el-pagination>
      </div>
    </div>
    <Vehicles :datas="coveredVehicles" ref="vehiclesRef"></Vehicles>
    <linkProducts :datas="allProducts" ref="linkProductsRef"></linkProducts>
    <HotVehicles :datas="hotVehicles" ref="hotVehiclesRef"></HotVehicles>
    <infoDialog ref="infoDialogRef" @getTable="getTableInfo"></infoDialog>
    <priceDialog ref="priceDialogRef" @getTable="getTableInfo"></priceDialog>
    <copyDialog ref="copyDialogRef" @getTable="getTableInfo"></copyDialog>
    <quickDialog ref="quickDialogRef" @getTable="getTableInfo"></quickDialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, onUnmounted, provide, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  deletePriceApi,
  getCoveredVehiclesApi,
  getPriceListApi,
  getProductOptionsApi,
  getVehicleOptionsApi,
} from "@/api/carfilm/quote";
import Vehicles from "./components/vehicles.vue";
import linkProducts from "./components/linkProducts.vue";
import HotVehicles from "./components/hotVehicles.vue";
import infoDialog from "./components/infoDialog.vue";
import priceDialog from "./components/priceDialog.vue";
import copyDialog from "./components/copyDialog.vue";
import quickDialog from "./components/quickDialog.vue";
import * as echarts from "echarts";
const dataLoading = ref(true);
const loading = ref(true);
const tableData = ref<any[]>([]);
const pageSize = ref(10);
const totalDataNumber = ref(0);
const curPage = ref(1);
const dialogVisible = ref(false);
const isupload = ref(false);
const vehiclesRef = ref<any>(null);
const linkProductsRef = ref<any>(null);
const hotVehiclesRef = ref<any>(null);
const infoDialogRef = ref<any>(null);
const priceDialogRef = ref<any>(null);
const copyDialogRef = ref<any>(null);
const quickDialogRef = ref<any>(null);
const formInline = ref({
  vehicle_id: "",
  product_id: "",
  sort: "id_desc",
});
const quickTags = ref([
  {
    label: "价格<1000元",
    call: () => {
      advancedSearch.value = {
        minPrice: 0,
        maxPrice: 1000,
        keyword: "",
        dateRange: [],
      };
      quickTagindex.value = 0;
      getTableInfo();
    },
  },
  {
    label: "1000-3000元",
    call: () => {
      advancedSearch.value = {
        minPrice: 1000,
        maxPrice: 3000,
        keyword: "",
        dateRange: [],
      };
      quickTagindex.value = 1;
      getTableInfo();
    },
  },
  {
    label: "3000-5000元",
    call: () => {
      advancedSearch.value = {
        minPrice: 3000,
        maxPrice: 5000,
        keyword: "",
        dateRange: [],
      };
      quickTagindex.value = 2;
      getTableInfo();
    },
  },
  {
    label: "价格>5000元",
    call: () => {
      advancedSearch.value = {
        minPrice: 5000,
        maxPrice: 100000,
        keyword: "",
        dateRange: [],
      };
      quickTagindex.value = 3;
      getTableInfo();
    },
  },
  {
    label: "最近7天添加",
    call: () => {
      advancedSearch.value = {
        minPrice: 0,
        maxPrice: 100000,
        keyword: "",
        dateRange: [
          new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000).toISOString(),
          new Date().toISOString(),
        ],
      };
      quickTagindex.value = 4;
      getTableInfo();
    },
  },
  {
    label: "最近30天添加",
    call: () => {
      advancedSearch.value = {
        minPrice: 0,
        maxPrice: 100000,
        keyword: "",
        dateRange: [
          new Date(new Date().getTime() - 3 * 24 * 60 * 60 * 1000).toISOString(),
          new Date().toISOString(),
        ],
      };
      quickTagindex.value = 5;
      getTableInfo();
    },
  },
  {
    label: "仅热门车型",
    call: () => {
      advancedSearch.value = {
        minPrice: 0,
        maxPrice: 100000,
        keyword: "热门",
        dateRange: [],
      };
      quickTagindex.value = 6;
      getTableInfo();
    },
  },
]);
const quickTagindex = ref(-1);
watch(
  () => formInline.value,
  () => {
    getTableInfo();
  },
  {
    deep: true,
  }
);
const isAdvanced = ref(false);
const advancedSearch = ref({
  minPrice: 0,
  maxPrice: 1000000,
  keyword: "",
  dateRange: [] as string[],
});
const vehicles_search = ref({
  brands: "",
  firstletter: "",
  is_popular: false,
  keyword: "",
});
const allVehicles = ref<any[]>([]);
const brands = computed(() => {
  let val = allVehicles.value.map((item: any) => {
    return item.brand;
  });
  //去重
  return val.filter((item: any, index: number) => {
    return val.indexOf(item) === index;
  });
});
const vehicles = computed(() => {
  return allVehicles.value.filter((item: any) => {
    if (vehicles_search.value.brands) {
      if (item.brand != vehicles_search.value.brands) {
        return false;
      }
    }
    if (vehicles_search.value.firstletter) {
      if (item.firstletter != vehicles_search.value.firstletter) {
        return false;
      }
    }
    if (vehicles_search.value.is_popular) {
      if (item.is_popular != vehicles_search.value.is_popular) {
        return false;
      }
    }
    if (vehicles_search.value.keyword) {
      if (!item.model.includes(vehicles_search.value.keyword)) {
        return false;
      }
    }
    return true;
  });
});
provide("allVehicles", allVehicles);
const productOptions = ref<any[]>([]);
const produtType = ref("");
const showProductOptions = computed(() => {
  return productOptions.value.filter((item: any) => {
    if (produtType.value) {
      if (item.type != produtType.value) {
        return false;
      }
    }
    return true;
  });
});
provide("productOptions", productOptions);
const sortOptions = ref([
  { label: "最新添加", value: "id_desc" },
  { label: "最早添加", value: "id_asc" },
  { label: "价格 高到低", value: "price_desc" },
  { label: "价格 低到高", value: "price_asc" },
  { label: "生效日期 近到远", value: "date_desc" },
  { label: "生效日期 远到近", value: "date_asc" },
  { label: "按车型排序", value: "vehicle_asc" },
  { label: "按产品排序", value: "product_asc" },
]);
const chartSwitch = ref(true);
const formRef = ref<any>();
const form = ref({
  id: 0,
  brand: "",
  model: "",
  year: "",
  firstletter: "",
  logo_url: "",
  is_popular: 0,
});
const formRules = ref({
  brand: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
  model: [{ required: true, message: "请输入车型名称", trigger: "blur" }],
});
const dialogTitle = computed(() => {
  return form.value.id > 0 ? "编辑车型" : "添加车型";
});
const letter = ref([
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "O",
  "P",
  "Q",
  "R",
  "S",
  "T",
  "U",
  "V",
  "W",
  "X",
  "Y",
  "Z",
]);
const resetAdvancedSearch = () => {
  advancedSearch.value = {
    minPrice: 0,
    maxPrice: 10000,
    keyword: "",
    dateRange: [],
  };
};
const getData = () => {
  getCoveredVehiclesApi().then((res: any) => {
    coveredVehicles.value = res.data;
  });
  dataLoading.value = true;
  getPriceListApi({
    page: 1,
    limit: 9999,
  }).then((res: any) => {
    dataLoading.value = false;
    allDataVehicles.value = res.data?.list;
    // 更新图表数据
    getData1();
    getData2();
    getData3();
  });
};
const coveredVehicles = ref([]);
const hotModel = computed((): any[] => {
  return coveredVehicles.value.filter((item: any) => {
    return item.is_popular == 1;
  });
});
const allDataVehicles = ref([]);
const allBrands = computed(() => {
  let all = allDataVehicles.value.map((item: any) => {
    return item.brand;
  });
  return all.filter((item: any, index: number) => {
    return all.indexOf(item) === index;
  });
});
const allProducts = computed(() => {
  let all = allDataVehicles.value.map((item: any) => {
    return {
      product_name: item.product_name,
      product_id: item.product_id,
      product_type: item.product_type,
    };
  });
  let all_id = all.map((item: any) => {
    return item.product_id;
  });
  return all.filter((item: any, index: number) => {
    return all_id.indexOf(item.product_id) === index;
  });
});
//平均价格
const averagePrice = computed(() => {
  return (
    allDataVehicles.value.reduce((acc: number, cur: any) => {
      return acc + parseFloat(cur.base_price);
    }, 0) / allDataVehicles.value.length
  ).toFixed(2);
});
const hotVehicles = computed(() => {
  let hot_models = hotModel.value.map((item: any) => {
    return item.model;
  });
  let lists = allDataVehicles.value.filter((item: any) => {
    return hot_models.includes(item.model);
  });
  //获取对应的hoModel
  return lists.map((item: any) => {
    return {
      ...item,
      pricing_count: hotModel.value?.find((hot: any) => {
        return hot.model == item.model;
      })?.pricing_count,
    };
  });
});
const newVehicles = computed(() => {
  return allDataVehicles.value.filter((item: any) => {
    //生效日期在一周内
    let date = new Date(item.effective_date);
    let now = new Date();
    let diff = Math.abs(date.getTime() - now.getTime());
    if (diff > 7 * 24 * 60 * 60 * 1000) {
      return false;
    }
    return true;
  });
});
const minPrice = computed(() => {
  return allDataVehicles.value.reduce((acc: number, cur: any) => {
    return Math.min(acc, parseFloat(cur.base_price));
  }, 1000000);
});
const maxPrice = computed(() => {
  return allDataVehicles.value.reduce((acc: number, cur: any) => {
    return Math.max(acc, parseFloat(cur.base_price));
  }, 0);
});

/******************图表********************* */
const myChart1 = ref<any>(null);
const myChart2 = ref<any>(null);
const myChart3 = ref<any>(null);

// 计算价格区间分布
const priceRangeData = computed(() => {
  const ranges = [
    { name: "0-1000元", min: 0, max: 1000 },
    { name: "1000-3000元", min: 1000, max: 3000 },
    { name: "3000-5000元", min: 3000, max: 5000 },
    { name: "5000元以上", min: 5000, max: Infinity },
  ];

  const rangeCount: Record<string, number> = {};

  ranges.forEach((range) => {
    rangeCount[range.name] = allDataVehicles.value.filter((item: any) => {
      const price = parseFloat(item.base_price);
      return price >= range.min && (range.max === Infinity || price < range.max);
    }).length;
  });

  return Object.keys(rangeCount).map((name) => ({
    name,
    value: rangeCount[name],
  }));
});

// 计算品牌分布数据
const brandDistributionData = computed(() => {
  const brands = allDataVehicles.value.map((item: any) => item.brand);
  const brandCount: Record<string, number> = {};

  brands.forEach((brand: string) => {
    brandCount[brand] = (brandCount[brand] || 0) + 1;
  });

  // 只取前10个品牌，其他的合并为"其他"
  const sortedBrands = Object.keys(brandCount)
    .map((name) => ({ name, value: brandCount[name] }))
    .sort((a, b) => b.value - a.value);

  if (sortedBrands.length > 10) {
    const topBrands = sortedBrands.slice(0, 10);
    const otherBrands = sortedBrands.slice(10);
    const otherCount = otherBrands.reduce((sum, brand) => sum + brand.value, 0);

    if (otherCount > 0) {
      topBrands.push({ name: "其他", value: otherCount });
    }

    return topBrands;
  }

  return sortedBrands;
});

// 初始化图表
const initCharts = () => {
  myChart1.value = echarts.init(document.getElementById("productTypeChart"));
  myChart2.value = echarts.init(document.getElementById("priceRangeChart"));
  myChart3.value = echarts.init(document.getElementById("brandChart"));
  // 确保图表撑满容器
  setTimeout(() => {
    myChart1.value?.resize();
    myChart2.value?.resize();
    myChart3.value?.resize();
    chartSwitch.value = false;
  }, 100);
};
//获取图表数据
const getData1 = () => {
  const productTypes = allDataVehicles.value.map((item: any) => item.product_type);
  console.log(productTypes);
  const typeCount: Record<string, number> = {};
  productTypes.forEach((type: any) => {
    typeCount[type] = (typeCount[type] || 0) + 1;
  });
  console.log(typeCount);
  let option_data = Object.keys(typeCount).map((name) => ({
    name,
    value: typeCount[name],
  }));
  // 清除之前的图表数据
  myChart1.value?.clear();
  const option = {
    tooltip: {
      trigger: "item",
    },
    legend: {
      // Try 'horizontal'
      orient: "vertical",
      right: 10,
      top: "center",
    },
    series: [
      {
        name: "",
        type: "pie",
        radius: ["40%", "70%"],
        data: option_data,
      },
    ],
  };
  // 指定图表的配置项和数据
  myChart1.value.setOption(option, true);
};
const getData2 = () => {
  // 定义价格区间
  const priceRanges = [
    { name: "0-1000", min: 0, max: 1000 },
    { name: "1000-3000", min: 1000, max: 3000 },
    { name: "3000-5000", min: 3000, max: 5000 },
    { name: "5000-8000", min: 5000, max: 8000 },
    { name: "8000-10000", min: 8000, max: 10000 },
    { name: "10000以上", min: 10000, max: Infinity },
  ];

  // 计算每个价格区间的数量
  const rangeData = priceRanges.map((range) => {
    const count = allDataVehicles.value.filter((item: any) => {
      const price = parseFloat(item.base_price);
      return price >= range.min && (range.max === Infinity || price < range.max);
    }).length;

    return {
      name: range.name,
      value: count,
    };
  });
  // 清除之前的图表数据
  myChart2.value?.clear();
  // 配置柱状图选项
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: rangeData.map((item) => item.name),
      axisTick: {
        alignWithLabel: true,
      },
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        name: "价格区间",
        type: "bar",
        barWidth: "60%",
        data: rangeData.map((item) => item.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#83bff6" },
            { offset: 0.5, color: "#188df0" },
            { offset: 1, color: "#188df0" },
          ]),
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#2378f7" },
              { offset: 0.7, color: "#2378f7" },
              { offset: 1, color: "#83bff6" },
            ]),
          },
        },
        label: {
          show: true,
          position: "top",
          formatter: "{c}",
        },
      },
    ],
  };

  // 设置图表选项
  myChart2.value?.setOption(option, true);
};
const getData3 = () => {
  // 按品牌分组计算平均价格
  const brandPriceMap: Record<string, { total: number; count: number }> = {};

  allDataVehicles.value.forEach((item: any) => {
    const brand = item.brand;
    const price = parseFloat(item.base_price);

    if (!brandPriceMap[brand]) {
      brandPriceMap[brand] = { total: 0, count: 0 };
    }

    brandPriceMap[brand].total += price;
    brandPriceMap[brand].count += 1;
  });

  // 计算平均价格并转换为数组
  const brandAvgPriceData = Object.keys(brandPriceMap).map((brand) => {
    const { total, count } = brandPriceMap[brand];
    return {
      name: brand,
      value: parseFloat((total / count).toFixed(2)),
    };
  });

  // 按平均价格从高到低排序
  brandAvgPriceData.sort((a, b) => b.value - a.value);

  // 只取前10个品牌
  const top10Brands = brandAvgPriceData.slice(0, 10);

  // 清除之前的图表数据
  myChart3.value?.clear();
  // 配置柱状图选项
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      formatter: "{b}<br/>{a}: {c}元",
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "10%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: top10Brands.map((item) => item.name),
      axisTick: {
        alignWithLabel: true,
      },
      axisLabel: {
        rotate: 45,
        interval: 0,
      },
    },
    yAxis: {
      type: "value",
      axisLabel: {
        formatter: "{value} 元",
      },
    },
    series: [
      {
        name: "平均价格",
        type: "bar",
        barWidth: "60%",
        data: top10Brands.map((item) => item.value),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: "#83bff6" },
            { offset: 0.5, color: "#188df0" },
            { offset: 1, color: "#188df0" },
          ]),
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#2378f7" },
              { offset: 0.7, color: "#2378f7" },
              { offset: 1, color: "#83bff6" },
            ]),
          },
        },
        label: {
          show: true,
          position: "top",
          formatter: "{c}元",
        },
      },
    ],
  };

  // 设置图表选项
  myChart3.value?.setOption(option, true);
};
onMounted(() => {
  getVehicleOptionsApi({}).then((res: any) => {
    allVehicles.value = res.data;
  });
  getProductOptionsApi().then((res: any) => {
    productOptions.value = res.data;
  });
  getData();
  getTableInfo();
  // 初始化图表
  nextTick(() => {
    initCharts();
  });
});
const setLetter = (letter: string) => {
  if (vehicles_search.value.firstletter == letter) {
    vehicles_search.value.firstletter = "";
  } else {
    vehicles_search.value.firstletter = letter;
  }
};
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getTableInfo();
};
const handleCurrentChange = (val: number) => {
  curPage.value = val;
  getTableInfo();
};
function getTableInfo() {
  loading.value = true;
  getPriceListApi({
    page: curPage.value,
    limit: pageSize.value,
    ...formInline.value,
    advancedSearch: advancedSearch.value,
  }).then((res: any) => {
    tableData.value = res.data?.list;
    totalDataNumber.value = res.data?.total;
    loading.value = false;
  });
}
const handleInfo = (row?: any) => {
  infoDialogRef.value.dialogOpen(row);
};
const handlePrice = () => {
  priceDialogRef.value.dialogOpen();
};
const handleCopy = () => {
  copyDialogRef.value.dialogOpen();
};
const handleQuick = () => {
  quickDialogRef.value.dialogOpen();
};
const handleDelete = (id: number) => {
  ElMessageBox.confirm("确认要删除该价格策略吗?", "警告！", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deletePriceApi(id).then((res: any) => {
        getTableInfo();
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "删除已取消",
      });
    });
};
const selectedRows = ref<any[]>([]);
provide("selectedRows", selectedRows);
// 添加这个函数来处理选中行变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
  console.log("选中的行:", selection);
};
</script>
<style lang="scss" scoped>
.advanced-search-panel {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin: 10px 0;
  padding: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  animation: fadeIn-1b06b556 0.3s ease-in-out;
  width: 100%;
  flex-shrink: 0;
}

.count-tip {
  margin-top: 12px;
  color: #909399;
  font-size: 13px;
}

.letter-box {
  margin-top: 10px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .letter-item {
    padding: 5px 10px;
    margin-top: 5px;
    cursor: pointer;
    margin-right: 5px;
    border: 1px solid #d9ecff;
    border-radius: 4px;

    &.active {
      background-color: #409eff;
      color: #fff;
    }
  }
}

.count-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}

.brand-item {
  margin-bottom: 35px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 24px;
  transition: all 0.3s;

  .brand-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 22px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebeef5;

    .brand-left {
      display: flex;
      align-items: center;

      .brand-name {
        margin: 0 15px 0 15px;
        font-size: 18px;
        font-weight: 500;
        color: #303133;
      }
    }
  }
}

.tag-box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-top: 10px;

  .el-tag {
    margin-right: 5px;
  }
}

.chart-box {
  margin-top: 20px;
  padding-bottom: 30px;

  .chart-title {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .chart-title-left {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .card-box {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    flex-shrink: 0;

    .el-card {
      width: 23%;
      margin-top: 20px;

      ::v-deep(.el-card__body) {
        display: flex !important;
        align-items: center;

        .card-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 15px;
        }

        .card-val {
          .val {
            font-size: 24px;
            font-weight: 600;
            color: #303133;
            line-height: 1.2;
          }

          .label {
            font-size: 14px;
            color: #909399;
            margin-top: 5px;
          }
        }
      }
    }
  }
}

.chart-main {
  margin-top: 20px;

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .chart-header-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
}
</style>
